﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices.AccountManagement;
using System.Drawing;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ATTAR
{
    public partial class SplashScreen : Form
    {
        private string currentUser;
        DateTime startTime;
        bool workDone = false;
        
        public SplashScreen()
        {
            InitializeComponent();
            this.currentUser = "";
            this.startTime = DateTime.Now;
        }

        private void SplashScreen_Shown(object sender, EventArgs e)
        {
            this.backgroundWorker.RunWorkerAsync();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            TimeSpan elapsedTime = DateTime.Now.Subtract(startTime);

            //after 3 sec stop the timer   
            if (elapsedTime.Seconds >= 3)
            {
                timer.Stop();  
                ShowMainScreen();
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;

            try
            {
                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
                {
                    UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);
                    currentUser = up.DisplayName;
                }
            }
            catch (Exception ex)
            { };
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {   
            workDone = true;
        }
        
        private void ShowMainScreen()
        {
            //display mainform
            MainScreen mf = new MainScreen(this.currentUser);
            mf.FormClosed += mf_FormClosed;
            mf.Show();
            //hide this form
            this.Hide();
        }

        void mf_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Close();
        }
    }
}
